import requests
import json
import os

script_path = os.path.dirname(os.path.abspath(__file__))
#print(script_path)
json_path = os.path.join(script_path, 'city.json')
stasion = open(json_path, encoding='utf-8').read()

city =  json.loads(stasion)

#print(city)
#go_city = "广州南"
#to_city = "吴忠"
start_time = "2025-05-31" 
go_city = input("请输入出发城市：")
to_city = input("请输入到达城市：")
#start_time = input("请输入出发时间：")

try:
    url = f"https://kyfw.12306.cn/otn/leftTicket/queryU?leftTicketDTO.train_date={start_time}&leftTicketDTO.from_station={city[go_city]}&leftTicketDTO.to_station={city[to_city]}&purpose_codes=ADULT"
    res = requests.get(url, headers={
        'user-agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36"
    })
    if res.status_code != 200:
        print("没有直达车次")
        exit()
except Exception as e:
    print("请求出错：", e)
    exit()

headers = {
    'user-agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36",
    'cookie': "_uab_collina=174814771889963426845086; JSESSIONID=16A3BF8857FE98C8697512BDD36793F7; BIGipServerotn=1893269770.50210.0000; guidesStatus=off; highContrastMode=defaltMode; cursorStatus=off; BIGipServerpassport=786956554.50215.0000; route=6f50b51faa11b987e576cdb301e545c4; _jc_save_toStation=%u5434%u5FE0%2CWVJ; _jc_save_toDate=2025-05-25; _jc_save_wfdc_flag=dc; _jc_save_fromStation=%u5E7F%u5DDE%u5357%2CIZQ; _jc_save_fromDate=2025-05-28",
    'referer': "https://kyfw.12306.cn/otn/leftTicket/init?linktypeid=dc&fs=%E5%B9%BF%E5%B7%9E%E5%8D%97,IZQ&ts=%E5%90%B4%E5%BF%A0,WVJ&date=2025-05-25&flag=N,N,Y"
}

#向12306发送请求
res = requests.get(url, headers=headers)
page_num = 0
page = 0
JSON = res.json()
data = JSON['data']['result']
for i in data:
    index = i.split('|')
    #print(index)
    page_num += 1
    #for j  in index:
        #print(j, page, sep = '---序号是')
     #   page += 1
    checi     = index[3]#车次
    go_time   = index[8]#出发时间
    to_time   = index[9]#到达时间
    time      = index[10]#用时
    vip       = index[32]#特等座
    first     = index[31]#一等座
    second    = index[30]#二等座
    #page_num = 
    #写标题
    dit = {
        '序号':page_num,
        '车次':checi,
        '出发时间':go_time,
        '到达时间':to_time,
        '用时':time,
        '特等座':vip,
        '一等座':first,
        '二等座':second
    }
    print(dit)
resault = input("请输入对应的车次序号：")
#如果输入的车次序号不在page_num范围内则打印错误信息
if int(resault) > page_num or int(resault) < 1:
    print("输入的车次序号不在范围内\n")

#print(JSON)




